'use strict';

const _ = require('lodash');
const dayjs = require('dayjs');

const Service = require('egg').Service;

class AlertSvc extends Service {

  async upsertAlert(user_id, kw) {
    const {ctx} = this;

    const user = await ctx.service.userSvc.getUserById(user_id);
    const email = user.email;

    await ctx.model.Alert.findOneAndUpdate(
      {user_id},
      {$pull: {kws: kw}},
      {new: true, upsert: true, setDefaultsOnInsert: true}
    );

    await ctx.model.Alert.findOneAndUpdate(
      {user_id},
      {$push: {kws: {$each: [kw], $position: 0}}, $set: {email}},
      {new: true, upsert: true, setDefaultsOnInsert: true}
    );
  }


  async deleteAlert(user_id, kw) {
    const {ctx} = this;

    await ctx.model.Alert.findOneAndUpdate(
      {user_id},
      {$pull: {kws: kw}}
    );
  }


  async listAlerts(user_id) {
    const {ctx} = this;
    let data = await ctx.model.Alert.findOne({user_id}).lean();
    if (data) {
      return data;
    } else {
      const user = await ctx.service.userSvc.getUserById(user_id);
      const email = user.email;
      return {kws: [], delivery_hours: [8], email};
    }
  }


  async updateDeliveryHours(user_id, delivery_hours) {
    const {ctx} = this;

    const user = await ctx.service.userSvc.getUserById(user_id);
    const email = user.email;

    await ctx.model.Alert.updateOne(
      {user_id},
      {$set: {delivery_hours, email}},
      {new: true, upsert: true, setDefaultsOnInsert: true}
    )
  }


  async updateLastDeliveryAt(user_id, last_delivery_at) {
    const {ctx} = this;

    await ctx.model.Alert.updateOne(
      {user_id},
      {$set: {last_delivery_at}},
    )
  }


  async getAlertsToSendEmail(delivery_hours) {
    const {ctx} = this;

    const users = await ctx.model.Alert.find({
      delivery_hours,
      kws: {$exists: true, $ne: []}
    }).sort({updatedAt: -1}).lean();

    return users;
  }


  async getMatchingTopics(kws, last_delivery_at) {
    let data = await Promise.all(
      kws.map(async kw => {
        const topics = await this.service.topicSvc.getDeliveryTopics(kw, last_delivery_at);
        let clean_topics = [];
        topics.forEach(v => {
          const clean_topic = {
            id: v.id,
            title: v.title,
            intro: v.intro || '',
            // author_name: v.author_name + '&nbsp;&nbsp;&nbsp;&nbsp;' + this.ctx.helper.ago(v.createdAt),
            author_name: v.author_name,
            original_url: v.original_url || `https://taosha.club/topic/${v.id}`
          }

          clean_topic.intro = clean_topic.intro.substr(0, 80);
          if (clean_topic.intro.length == 80) {
            clean_topic.intro += '......';
          }

          clean_topics.push(clean_topic);
        })
        return {kw: kw, topics: clean_topics}
      })
    );

    let result = [];

    for (let i = 0; i < data.length; i++) {
      const item = data[i];
      if (item.topics.length > 0) {
        result.push(item);
      }
    }

    return result;
  }


}


module.exports = AlertSvc;
